package com.bnq.logc.utils

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream


class FileHelper {

    companion object {

        private val TAG = "FileHelper"

        fun copyFileFromUriToDataDir(context: Context, uri: Uri, destinationDirPath: String) {
            try {
                val contentResolver = context.contentResolver
                val inputStream = contentResolver.openInputStream(uri)
                val destinationDir = File(destinationDirPath)
                if (!destinationDir.exists()) {
                    destinationDir.mkdirs()
                }
                val displayName = getDisplayName(context, uri)
                val destinationFile = File(destinationDir, displayName)
                val outputStream: OutputStream = FileOutputStream(destinationFile)
                val buffer = ByteArray(1024)
                var length: Int
                while (inputStream!!.read(buffer).also { length = it } > 0) {
                    outputStream.write(buffer, 0, length)
                }
                inputStream.close()
                outputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        private fun getDisplayName(context: Context, uri: Uri): String? {
            var displayName: String? = null
            var cursor: Cursor? = null
            try {
                cursor = context.contentResolver.query(uri, null, null, null, null)
                if (cursor != null && cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                    if (index != -1) {
                        displayName = cursor.getString(index)
                    }
                }
            } finally {
                cursor?.close()
            }
            return displayName
        }

        /**
         * 获取外部存储区域Download的 uri
         */
        fun getExternalDownloadsUri(context: Context,fileName:String):Uri?{
            val parentPath = context.packageName + File.separator + "logc/temp/${DateUtil.getCurrentYMDString(System.currentTimeMillis())}"
            return if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                val externalFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                val destFile = File(externalFile.absolutePath + File.separator + parentPath)
                if(!destFile.exists()){
                    destFile.mkdirs()
                }
                val outFile = File(destFile,fileName)
                Uri.fromFile(outFile)
            } else {
                val resolver = context.contentResolver
                val values = ContentValues()
                values.put(MediaStore.Downloads.DISPLAY_NAME, fileName)
                //values.put(MediaStore.Downloads.MIME_TYPE, "text/plain")
                values.put(MediaStore.Downloads.TITLE, fileName)
                values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + File.separator + parentPath)//保存路径
                val uri = MediaStore.Downloads.EXTERNAL_CONTENT_URI//MediaStore.Files.getContentUri("external")
                resolver.insert(uri, values)
            }
        }


        /**
         * 拷贝沙盒中的文件到外部存储区域
         * @param filePath 沙盒文件路径
         * @param  externalUri 外部存储文件的 uri
         */
        fun copySandFileToExternalUri(
            context: Context,
            filePath: String?,
            externalUri: Uri?
        ): Boolean {
            val contentResolver = context.contentResolver
            var inputStream: InputStream? = null
            var outputStream: OutputStream? = null
            var ret = false
            try {
                outputStream = contentResolver.openOutputStream(externalUri!!)
                val sandFile = File(filePath)
                if (sandFile.exists()) {
                    inputStream = FileInputStream(sandFile)
                    var readCount = 0
                    val buffer = ByteArray(1024)
                    while (inputStream.read(buffer).also { readCount = it } != -1) {
                        outputStream!!.write(buffer, 0, readCount)
                        outputStream.flush()
                    }
                }
                ret = true
            } catch (e: Exception) {
                Log.e(TAG, "copy SandFile To ExternalUri. e = $e")
                ret = false
            } finally {
                try {
                    outputStream?.close()
                    inputStream?.close()
                    Log.d(TAG, " input stream and output stream close successful.")
                } catch (e: Exception) {
                    e.printStackTrace()
                    Log.e(TAG, " input stream and output stream close fail. e = $e")
                }
                return ret
            }
        }

        fun copyFile(sourceFile: File, destFile: File): Boolean {
            var inputStream: InputStream? = null
            var outputStream: OutputStream? = null
            return try {
                inputStream = FileInputStream(sourceFile)
                outputStream = FileOutputStream(destFile)
                val buffer = ByteArray(1024)
                var length: Int
                while (inputStream.read(buffer).also { length = it } > 0) {
                    outputStream.write(buffer, 0, length)
                }
                true // 文件复制成功
            } catch (e: IOException) {
                e.printStackTrace()
                false // 文件复制失败
            } finally {
                try {
                    inputStream?.close()
                    outputStream?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

}